const api = require('/api.js')
const app = getApp()
const formatTime = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}
/**
 *微信showToast提示
 @msg为提示信息
 @icon为提示图标
 */
function showToast(msg, icon) {
	wx.showToast({
		title: msg,
		icon: icon
	})
}

/**图片预览
 * @src 为当前点击图片路径 String
 * @list为预览图片的整个数组 Object
 */
function previewPhoto(src, list) {
	wx.previewImage({
		current: src,
		urls: list
	})
}


/**存储formid
 * @formId 为存储formid
 */
function saveFromId(formId) {
	// api.saveFrormid({
	//   data: {
	//     formid: formId
	//   },
	//   success: res => {

	//   }
	// })
}
/**
 * 授权信息
 * @that为页面指向 Object
 * @userInfo为iv,signature,code,encryptedData等解密信息  Object
 * 
 */
function saveUserInfo(that, userInfo) {
	return new Promise(function(resolve, reject) {
		var userInfoData = userInfo
		userInfoData.type = api.come_from
		userInfoData.token = wx.getStorageSync('token') || app.globalData.token;
		console.log(userInfoData);
		api.saveUserInfo({
			data: userInfoData,
			success: res => {
				console.log(res.data.result.uname);
				app.globalData.openid = res.data.result.openid;
				app.globalData.authStatus = true;
				app.globalData.userInfo = res.data.result
				app.globalData.uid = res.data.result.uid;
				app.globalData.uname = res.data.result.uname;
				wx.setStorageSync('openid', res.data.result.openid)
				wx.setStorageSync('uid', res.data.result.uid)
				that.setData({
					authStatus: true
				})
				resolve(res)
			},
			fail: res => {
				reject(res)
			}
		})
	})
}

/**
 * wx.login登录信息
 * resolve为promise的执行判断
 */
function getLogin(resolve) {
	let that = this
	// wx.showLoading({
	//   title: '加载中',
	// })
	wx.login({
		success: res => {
			// 发送 res.code 到后台换取 openId, sessionKey, unionId
			//獲取openid
			let code = res.code;
			app.globalData.code = code
			wx.request({
				url: api.host + "/user/login",
				method: "POST",
				data: {
					code: code,
					scene: res.scene,
					type: api.come_from
				},
				header: {
					"Cotent-Type": 'application/json'
				},
				success: (res) => {
					if (res.statusCode == 200) {
						console.log(123,res.data.result)
						app.globalData.userInfo = res.data.result
						app.globalData.userInfo.code = code
						// app.globalData.openid = res.data.result.openid;
						// app.globalData.uid = res.data.result.uid;
						app.globalData.isShow = false;
						app.globalData.loginStatus = true;
						app.globalData.authStatus = res.data.result.uid == 0  ? false : true//|| res.data.result.update == 1
						app.globalData.token = res.data.token;
						wx.setStorageSync('openid', res.data.result.openid)
						wx.setStorageSync('token', res.data.token)
						wx.setStorageSync('uid', res.data.result.uid)
						resolve()
					} else {
						let options
						// that.getLogin(options, resolve)
					}
				},
				fail: res => {
					// 微信登录失败
					// that.implementOrder(1);
					that.wxLogin();
				},

			})
		}
	})
}

/**
 * 截取字符串 中英文混合
 *  str	待处理字符串
 *  len	截取字节长度 中文2字节 英文1字节
 *  add 是否加上...
 */
const subString = function(str, len, add) {
	var regexp = /[^\x00-\xff]/g; // 正在表达式匹配中文
	if (str == null) {
		return;
	}
	if (typeof str != "string") {
		str = str.toString();
	}
	// 当字符串字节长度小于指定的字节长度
	if (str.replace(regexp, "aa").length <= len) {
		return str;
	}
	// 假设指定长度内都是中文
	var m = Math.floor(len / 2);
	for (var i = m, j = str.length; i < j; i++) {
		// 当截取字符串字节长度满足指定的字节长度
		if (str.substring(0, i).replace(regexp, "aa").length >= len) {
			if (!add) {
				var return_str = str.substring(0, i);
				var last_str = return_str.substring(return_str.length - 1, return_str.length);
				if (charToUnicode(last_str) == '/ud83d') {
					var return_str = str.substring(0, i - 1);
				};
				return return_str + '...';
			} else {
				return str.substring(0, i);
			}
		}
	}
	return str;
}

export const formatTime2 = function(timestamp, format) {
    var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
    var returnArr = [];
	if (timestamp.toString().length==10){
		var date = new Date(timestamp * 1000);
    }else{
		var date = new Date(timestamp);
    }
    returnArr.push(date.getFullYear());
    returnArr.push(formatNumber(date.getMonth() + 1));
    returnArr.push(formatNumber(date.getDate()));

    returnArr.push(formatNumber(date.getHours()));
    returnArr.push(formatNumber(date.getMinutes()));
    returnArr.push(formatNumber(date.getSeconds()));

    for (var i in returnArr) {
        format = format.replace(formateArr[i], returnArr[i]);
    }
    return format;
}

module.exports = {
	formatTime: formatTime,
	previewPhoto,
	saveUserInfo,
	getLogin,
	showToast,
	saveFromId,
	subString,
	formatTime2
}
